/**
 * 2025/01/01 - 2025/12/31
 */
package com.snail.server.iam.login.manager;

import com.snail.server.iam.account.entity.Account;
import com.snail.server.iam.account.service.AccountService;
import com.snail.server.iam.app.entity.App;
import com.snail.server.iam.app.service.AppService;
import com.snail.server.iam.enums.LoginTypeEnum;
import com.snail.server.iam.login.dto.LoginDTO;
import com.snail.server.iam.login.vo.LoginVO;
import com.snail.server.iam.user.service.UserService;
import com.snail.starter.commons.threadlocal.UserContext;
import com.snail.starter.commons.threadlocal.UserContextUtils;
import com.snail.starter.iam.authentication.local.token.ITokenService;
import com.snail.starter.utils.lambda.GenericEntityBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author zgadmin
 * @date 2025/9/24 17:39
 */
@Component
public class LoginManager {

    @Resource
    AppService appService;

    @Resource
    AccountService accountService;

    @Resource
    UserService userService;

    @Resource
    ITokenService tokenService;

    public LoginVO login(LoginDTO loginDTO) {
        App app = appService.checkAppByKey(loginDTO.getAppKey());
        Account account = accountService.checkAccountByName(loginDTO.getLoginName(), loginDTO.getPassword(), null != loginDTO.getLoginType() && loginDTO.getLoginType().equals(LoginTypeEnum.MOBILE.getCode()));
        UserContext userContext = userService.login(loginDTO.getTenantId(), app, account, app.getUserType());
        UserContextUtils.set(userContext);
        return GenericEntityBuilder.of(LoginVO::new)
                .withSupplier(LoginVO::setTenantId, userContext::getTenantId)
                .withSupplier(LoginVO::setAppKey, userContext::getAppKey)
                .withSupplier(LoginVO::setName, userContext::getName)
                .withSupplier(LoginVO::setToken, userContext::getToken)
                .build();
    }

    public boolean logout() {
        tokenService.destroy(UserContextUtils.get().getToken());
        return false;
    }

}